<template>
  <div>
    <el-button type="danger" @click="batchDelete">批量删除</el-button>
    <!-- 树形菜单 -->
    <el-tree
      :data="menus"
      :props="defaultProps"
      @node-click="handleNodeClick"
      :expand-on-click-node="false"
      show-checkbox
      node-key="catId"
      :default-expanded-keys="expandedKeys"
      ref="menuTree"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button v-if="node.level <= 2" type="text" size="mini" @click="() => append(data)">添加</el-button>
          <el-button type="text" size="mini" @click="() => edit(data)">修改</el-button>
          <el-button
            v-if="node.childNodes.length == 0"
            type="text"
            size="mini"
            @click="() => remove(node, data)"
          >删除</el-button>
        </span>
      </span>
    </el-tree>

    <!-- 对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="category.icon" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input v-model="category.productUnit" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitData()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  //import 引入的组件需要注入到对象中才能使用
  components: {},
  props: {},
  data() {
    //这里存数据
    return {
      menus: [],
      defaultProps: {
        children: "children",
        label: "name"
      },
      expandedKeys: [],
      dialogVisible: false,
      dialogType: "",
      category: {
        name: "",
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 0,
        catId: null,
        icon: "",
        productUnit: ""
      },
      title: ""
    }
  },
  //计算属性
  computed: {},
  //监控data中数据变化
  watch: {},
  //方法
  methods: {
    //函数的data绑定的是:data="menus"
    handleNodeClick(data) {},

    getMenus() {
      this.$http({
        url: this.$http.adornUrl("/product/category/list/tree"),
        method: "get"
      }).then(({ data }) => {
        this.menus = data.data
      })
    },

    batchDelete() {
      let catIds = []
      let categoryName = []
      let checkedNodes = this.$refs.menuTree.getCheckedNodes()
      for (let i = 0; i < checkedNodes.length; i++) {
        catIds.push(checkedNodes[i].catId)
        categoryName.push(checkedNodes[i].name)
      }
      this.$confirm(`是否批量删除:${categoryName}菜单?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(catIds, false)
          }).then(({ data }) => {
            this.$message({
              message: "菜单批量删除成功",
              type: "success"
            })
            this.getMenus()
          })
        })
        .catch(() => {
          //关闭对话框
          this.dialogVisible = false
        })
    },

    // 提交数据
    submitData() {
      if (this.dialogType == "add") {
        this.addCategory()
      }
      if (this.dialogType == "edit") {
        this.editCategory()
      }
    },

    //添加三级分类数据
    append(data) {
      //打开对话框
      this.dialogType = "add"
      this.title = "添加分类"
      this.dialogVisible = true
      this.category.parentCid = data.catId
      this.category.catLevel = data.catLevel * 1 + 1
      //清空对话框回显的内容
      this.category.name = ""
      this.category.icon = ""
      this.category.productUnit = ""
      this.category.sort = 0
      this.category.showStatus = 1
    },

    //回显修改的菜单的最新数据，保证修改拿到的都是最新数据，避免被默认值替换
    edit(data) {
      console.log(data)
      this.dialogType = "edit"
      this.title = "修改分类"
      this.dialogVisible = true
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: "get"
      }).then(({ data }) => {
        let categoryResult = data.data
        console.log("要回显的数据", categoryResult)
        this.category.name = categoryResult.name
        this.category.catId = categoryResult.catId
        this.category.icon = categoryResult.icon
        this.category.parentCid = categoryResult.parentCid
        this.category.productUnit = categoryResult.productUnit
      })
    },

    //提交修改数据
    editCategory() {
      //结构表达式
      var { catId, name, icon, productUnit } = this.category
      //key,value相同，可省略key  -----es6
      var data = {
        catId,
        name,
        icon,
        productUnit
      }
      this.$http({
        url: this.$http.adornUrl("/product/category/update"),
        method: "post",
        data: this.$http.adornData(data, false)
      }).then(({ data }) => {
        this.$message({
          message: "修改菜单成功",
          type: "success"
        })
        //关闭对话框
        this.dialogVisible = false
        //刷新菜单
        this.getMenus()
        //默认展开的菜单
        this.expandedKeys = [this.category.parentCid]
      })
    },

    //添加3级分类
    addCategory() {
      console.log(this.category)
      this.$http({
        url: this.$http.adornUrl("/product/category/save"),
        method: "post",
        data: this.$http.adornData(this.category, false)
      }).then(({ data }) => {
        this.$message({
          message: "菜单添加成功",
          type: "success"
        })
        //关闭对话框
        this.dialogVisible = false
        //刷新菜单
        this.getMenus()
        //默认展开的菜单
        this.expandedKeys = [this.category.parentCid]
      })
    },
    //删除菜单
    remove(node, data) {
      var ids = [data.catId]
      this.$confirm(`是否删除${data.name}菜单?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false)
          }).then(({ data }) => {
            this.$message({
              message: "菜单删除成功",
              type: "success"
            })
            //刷新菜单
            this.getMenus()
            //默认展开的菜单
            this.expandedKeys = [node.parent.data.catId]
          })
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          })
        })
    }
  },
  //声明周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getMenus()
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //声明周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁之后
  activated() {} //缓存keep-alive
}
</script>

<style scoped>
</style>